package com.wxs.controller;

import com.wxs.exception.CustomException;
import com.wxs.po.*;
import com.wxs.service.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.*;

@Controller
@RequestMapping(value = "/signIn")
public class TSignInController {

    @Resource(name = "teacherServiceImpl")
    private TeacherService teacherService;
    @Resource(name = "studentCourseServiceImpl")
    private StudentCourseService studentCourseService;
    @Resource(name = "userloginServiceImpl")
    private UserloginService userloginService;
    @Resource(name = "courseServiceImpl")
    private CourseService courseService;
    @Resource(name = "TSignInServiceImpl")
    private TSignInService tSignInService;
    @Resource(name = "studentServiceImpl")
    private StudentService studentService;
    @Resource(name = "TSignInStudentServiceImpl")
    private TSignInStudentService tSignInStudentService;
    /**
     * 获取当前登陆用户名的id
     *
     * @return
     */
    private Integer getUserId() throws Exception {
        Userlogin userlogin = userloginService.findByName(getUserName());
        return userlogin.getId();
    }

    /**
     * 获取当前用户名
     *
     * @return 用户名
     */
    private String getUserName() {
        Subject subject = SecurityUtils.getSubject();
        String userName = (String) subject.getPrincipal();
        return userName;
    }

    /**
     * 获取CourseCustom列表
     * @param list
     * @return
     * @throws Exception
     */
    private List<CourseCustom> getCourseCustomList(List<Course> list) throws Exception{
        List<CourseCustom> lists = new ArrayList<CourseCustom>();
        for (Course course: list) {
            lists.add(getCourseCustom(course));
        }
        return lists;
    }
    /**
     * 获取CourseCustom
     * @param course
     * @return
     * @throws Exception
     */
    private CourseCustom getCourseCustom(Course course) throws Exception{
        CourseCustom courseCustom = new CourseCustom();
        BeanUtils.copyProperties(course, courseCustom);
        Teacher teacher = teacherService.findById(course.getTeacherId());
        courseCustom.setTeacherName(teacher.getName());

        return courseCustom;
    }

    /**
     * 获取StudentCourseCustom
     * @param studentCourse
     * @return
     * @throws Exception
     */
    private StudentCourseCustom getStudentCourseCustom(StudentCourse studentCourse) throws Exception{
        Course course = courseService.findById(studentCourse.getCourseId());
        String teacherName = teacherService.findById(course.getTeacherId()).getName();

        StudentCourseCustom studentCourseCustom = new StudentCourseCustom();
        BeanUtils.copyProperties(studentCourse, studentCourseCustom);
        studentCourseCustom.setCourse(course);
        studentCourseCustom.setTeacherName(teacherName);


        return studentCourseCustom;
    }

    /**
     * 获取StudentCourseCustom列表
     * @param list
     * @return
     * @throws Exception
     */
    private List<StudentCourseCustom> getStudentCourseCustomList(List<StudentCourse> list) throws Exception{
        List<StudentCourseCustom> lists = new ArrayList<StudentCourseCustom>();
        for (StudentCourse studentCourse: list) {
            lists.add(getStudentCourseCustom(studentCourse));
        }
        return lists;
    }



    @RequestMapping(value = "/showCourse")
    public String showCourse(Model model, Integer page) throws Exception {

//        List<Course> list = null;
//        //页码对象
//        PagingVO pagingVO = new PagingVO();
//        //设置总页数
//        pagingVO.setTotalCount(courseService.getCountCourse());
//        if (page == null || page == 0) {
//            pagingVO.setToPageNo(1);
//            list = courseService.findByPaging(1);
//        } else {
//            pagingVO.setToPageNo(page);
//            list = courseService.findByPaging(page);
//        }
//
//        List<CourseCustom> lists = getCourseCustomList(list);
//        model.addAttribute("courseList", lists);
//        model.addAttribute("pagingVO", pagingVO);
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            long timeInMillis = calendar.getTimeInMillis();
            Timestamp nowTime = new Timestamp(timeInMillis);
            List<Course> list = courseService.findByTeacherID(getUserId());
            List<Map> results = new ArrayList();
            for (Course course : list) {
                int id = course.getId();
                System.out.println(id);
                int courseNum = tSignInService.getCourseNum(id);
                String state = "true";
                TSignIn tSignIn = tSignInService.findAllCourseById(id);
                if (tSignIn != null) {
                    Timestamp timestamp = tSignIn.getTime();
                    if (nowTime.before(timestamp)) {
                        state = "false";
                    }
                }
                Map<String, String> result = new HashMap<String, String>();
                result.put("id", course.getId().toString());
                result.put("name", course.getName());
                result.put("num", String.valueOf(courseNum));
                result.put("state", state);
                results.add(result);
            }
            model.addAttribute("courseList", results);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "teacher/signIn";
    }

    @ResponseBody
    @PostMapping("/submit")
    public String submit(@RequestBody Map<String, Object> params) {
        try {

            int courserId = (Integer) params.get("signInId");
            tSignInService.insertSignIn(courserId);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }

    @RequestMapping("/list")
    public String list(Integer id, Model model){
        try {
            List<TSignIn> signInList = tSignInService.findSignInListById(id);
            List<Map> courseList = new ArrayList();
            Course course = courseService.findById(id);
            String name=course.getName();
            for (TSignIn tSignIn : signInList) {
                Map<String, String> results = new HashMap<String, String>();
                results.put("id", String.valueOf(tSignIn.getId()));
                results.put("name", name);
                results.put("time", String.valueOf(tSignIn.getTime()));
                results.put("total", String.valueOf(tSignIn.getTotal()));
                courseList.add(results);
            }
            model.addAttribute("courseList", courseList);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "teacher/signIn_list";

    }


    @RequestMapping("/detail")
    public String detail(Integer id, Model model){
        try {
            List<TSignInStudent> students = tSignInService.findStudentById(id);
            List<Map> studentList = new ArrayList();
            for (TSignInStudent student : students) {
                Student student1 = studentService.findById(student.getStudentId());
                System.out.println(student.toString());
                System.out.println(student.getStudentId());
                Map<String, String> results = new HashMap<String, String>();
                results.put("id", String.valueOf(student1.getId()));
                results.put("name",student1.getName());
                results.put("time", String.valueOf(student.getTime()));
                studentList.add(results);
            }
            model.addAttribute("studentList", studentList);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "teacher/signIn_detail";

    }

    @RequestMapping("/student")
    public String studentSignIn(Integer id, Model model) throws Exception {
        int stuId = getUserId();
        try{
            List<Map> results=new ArrayList<Map>();
            List<StudentCourse> list = studentCourseService.findByStudentID(stuId, false);
            List<StudentCourseCustom> lists = getStudentCourseCustomList(list);
            for (StudentCourseCustom studentCourseCustom : lists) {
                Integer courseId = studentCourseCustom.getCourse().getId();
                TSignIn tSignIn = tSignInService.findAllCourseById(courseId);
                int state=tSignInStudentService.checkCourse(courseId,stuId);
                if(state==2||state==3){
                    Map<String,String> result=new HashMap<String, String>();
                    result.put("id", String.valueOf(courseId));
                    result.put("name",studentCourseCustom.getCourse().getName());
                    result.put("teacherName",studentCourseCustom.getTeacherName());
                    result.put("i", String.valueOf(tSignIn.getId()));
                    if(state==2)
                        result.put("state","2");
                    if(state==3)
                        result.put("state","3");
                    results.add(result);
                }
            }
            model.addAttribute("student", results);
        }
        catch (Exception e){
            throw  new CustomException("未获取到已选课程！");
        }
        return "student/signIn";
    }

    @ResponseBody
    @PostMapping("/student/submit")
    public String studentSubmit(@RequestBody Map<String, Object> params){
        try {
            int i = (Integer) params.get("signInId");
            System.out.println(i);
            System.out.println("AAA");
            tSignInStudentService.updateSignIn(i);
            long timeInMillis = Calendar.getInstance().getTimeInMillis();
            Timestamp date = new Timestamp(timeInMillis);
            int stuId = getUserId();
            tSignInStudentService.insertSignInStudent(i,stuId,date);

        }catch (Exception e){
            e.printStackTrace();
        }
        return "success";

    }

}
